package com.fbt.transfer.app.driver.ui.me;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import cn.hutool.core.text.CharSequenceUtil;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.fbt.transfer.app.driver.R;
import com.fbt.transfer.app.driver.activity.LoginActivity;
import com.fbt.transfer.app.driver.activity.MyBalanceActivity;
import com.fbt.transfer.app.driver.databinding.FragmentMeBinding;
import com.fbt.transfer.app.driver.model.ProfileInfo;
import com.fbt.transfer.app.driver.model.Result;
import com.fbt.transfer.app.driver.util.UserManager;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MeFragment extends Fragment {

  private FragmentMeBinding binding = null;
  private MeViewModel meViewModel = null;

  public View onCreateView(@NonNull LayoutInflater inflater,
      ViewGroup container, Bundle savedInstanceState) {
    meViewModel = new ViewModelProvider(this).get(MeViewModel.class);

    binding = FragmentMeBinding.inflate(inflater, container, false);
    View root = binding.getRoot();

    initObservers();
    initListeners();

    return root;
  }

  private void initObservers() {
    // 观察加载状态
    meViewModel.getIsLoading().observe(
        getViewLifecycleOwner(), isLoading -> {
          // 可以在这里添加加载指示器
        }
    );

    // 观察错误消息
    meViewModel.getErrorMessage().observe(
        getViewLifecycleOwner(), errorMsg -> {
          if (!TextUtils.isEmpty(errorMsg)) {
            Toast.makeText(requireContext(), errorMsg, Toast.LENGTH_SHORT).show();
          }
        }
    );

    // 观察个人信息数据
    meViewModel.getProfileInfo().observe(getViewLifecycleOwner(), this::updateUI);
  }

  private void initListeners() {
    // 我的余额
    binding.llMyBalance.setOnClickListener(v -> {
      Toast.makeText(requireContext(), "我的余额", Toast.LENGTH_SHORT).show();
      // TODO: 跳转到余额页面MyBalanceActivity
      Intent intent = new Intent(requireContext(), MyBalanceActivity.class);
      startActivity(intent);
    });

    // 历史订单
    binding.llOrderHistory.setOnClickListener(v -> {
      Toast.makeText(requireContext(), "历史订单", Toast.LENGTH_SHORT).show();
      // TODO: 跳转到历史订单页面
    });

    // 乘客评价
    binding.llPassengerReviews.setOnClickListener(v -> {
      Toast.makeText(requireContext(), "乘客评价", Toast.LENGTH_SHORT).show();
      // TODO: 跳转到乘客评价页面
    });

    // 设置
    binding.llSettings.setOnClickListener(v -> {
      Intent intent = new Intent(
          requireContext(), com.fbt.transfer.app.driver.ui.settings.SettingsActivity.class);
      startActivity(intent);
    });

    // 退出登录
    binding.btnLogout.setOnClickListener(v -> logout());
  }

  private void updateUI(ProfileInfo profileInfo) {
    if (profileInfo == null) {
      return;
    }
    // 设置手机号
    String phoneNumber = profileInfo.getPhone();
    if (!TextUtils.isEmpty(phoneNumber) && phoneNumber.length() > 7) {
      // 隐藏中间4位数字
      phoneNumber = phoneNumber.substring(0, 3) + "****" + phoneNumber.substring(7);
    }
    // 设置用户名
    binding.tvName.setText(
        CharSequenceUtil.format(
            "{}({})",
            profileInfo.getName(), phoneNumber
        )
    );
    // 设置车辆信息
    binding.tvCarBrandType.setText(profileInfo.getCarBand());
    binding.tvCarNo.setText("车牌：" + profileInfo.getCarNo());
    binding.tvServiceType.setText(profileInfo.getCarType().getDesc());

    // 设置头像
    if (CharSequenceUtil.isNotBlank(profileInfo.getHeadPic())) {
      Glide.with(this)
          .load(profileInfo.getHeadPic())
          .apply(RequestOptions.circleCropTransform())
          .placeholder(
              profileInfo.getSex() == null || profileInfo.getSex() == 1 || profileInfo.getSex() == 0
                  ?
                  R.drawable.man : R.drawable.woman)
          .error(
              profileInfo.getSex() == null || profileInfo.getSex() == 1 || profileInfo.getSex() == 0
                  ?
                  R.drawable.man : R.drawable.woman)
          .into(binding.ivAvatar);
    } else {
      binding.ivAvatar.setImageResource(
          profileInfo.getSex() == null || profileInfo.getSex() == 1 || profileInfo.getSex() == 0 ?
              R.drawable.man : R.drawable.woman);
    }
    // 设置订单数量
    binding.tvOrderCount.setText(profileInfo.getCount());
    binding.tvTotalIncome.setText(profileInfo.getTotalIncome());
  }

  private void logout() {
    // 先清除本地用户数据
    UserManager.getInstance(requireContext()).clearUserInfo();

    // 调用退出登录接口，但不关心结果
    meViewModel.logout(new Callback<Result<Boolean>>() {
      @Override
      public void onResponse(Call<Result<Boolean>> call, Response<Result<Boolean>> response) {
        // 无论接口是否成功，都跳转到登录页面
        navigateToLoginPage();
      }

      @Override
      public void onFailure(Call<Result<Boolean>> call, Throwable t) {
        // 网络请求失败，也跳转到登录页面
        navigateToLoginPage();
      }
    });
  }

  private void navigateToLoginPage() {
    // 结束当前Activity
    requireActivity().finish();
    // 跳转到登录页面
    Intent intent = new Intent(requireContext(), LoginActivity.class);
    startActivity(intent);
  }

  @Override
  public void onDestroyView() {
    super.onDestroyView();
    binding = null;
  }
}
